package org.idea.spring.bean.beaninstance;

import org.idea.spring.bean.beaninstance.factory.DefaultUserFactory;
import org.idea.spring.bean.beaninstance.factory.UserFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.serviceloader.ServiceLoaderFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 借助spring的serviceloader来加载spring内部的bean
 *
 * @Author idea
 * @Date created in 5:21 下午 2020/7/5
 */
public class ServiceLoaderBeanInstanceDemo {

    public static void createBeanWithJdkWay(){
        ServiceLoader serviceLoader = ServiceLoader.load(UserFactory.class,Thread.currentThread().getContextClassLoader());
        displayServiceLoader(serviceLoader);
    }

    public static void displayServiceLoader(ServiceLoader serviceLoader){
        Iterator<UserFactory> iterator = serviceLoader.iterator();
        while (iterator.hasNext()) {
            UserFactory userFactory = iterator.next();
            System.out.println(userFactory.createUser());
        }
    }

    public static void main(String[] args) {
//        BeanFactory beanFactory = new ClassPathXmlApplicationContext("special-bean-instance-context.xml");
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("special-bean-instance-context.xml");
        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
        ServiceLoader serviceLoader = autowireCapableBeanFactory.getBean("specialServiceLoaderFactoryBean",ServiceLoader.class);
        displayServiceLoader(serviceLoader);

        UserFactory userFactory = autowireCapableBeanFactory.createBean(DefaultUserFactory.class);
        System.out.println(userFactory.createUser());
//        createBeanWithJdkWay();
    }
}
